/*
 * Copyright (c) 2021
 * User:魔金多商户商城
 * File:WechatCodeUtils.java
 * Date:2021/01/11 21:00:11
 */

package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.bean.WechatCodeSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
public class WechatCodeUtils {

    /**
     * 获取微信小程序access_token（有效期两小时）
     *
     * @param wechatSetting 微信设置实体
     * @return 微信小程序access_token
     */
    public static String getAccessToken(WechatCodeSetting wechatSetting) {
        log.debug("getAccessToken and wechatSetting:{} ", wechatSetting);
        String accessTokenForShareUrl = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
        JSONObject res = JSON.parseObject(CustomHttpUtils.postJson(accessTokenForShareUrl, JSON.toJSONString(wechatSetting)));
        if (!org.springframework.util.StringUtils.isEmpty(res.getString("errcode"))) {
            if (!StringUtils.isEmpty(res.getString("errmsg"))) {
                log.error("getAccessToken Fail and errmsg:{}", res.getString("errmsg"));
            }
            return null;
        } else {
            return res.getString("access_token");
        }
    }

    /**
     * 获取代码草稿列表
     * https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Mini_Programs/code_template/gettemplatedraftlist.html
     *
     * @param wechatSetting 微信设置实体
     * @return 微信小程序access_token
     */
    public static String getDraftList(WechatCodeSetting wechatSetting) {
        // 设置获取微信小程序码接口调用凭证
        String accessToken = getAccessToken(wechatSetting);
        String url = "https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=%s";

        String json = CustomHttpUtils.doGet(String.format(url, accessToken));
        return json;
    }


    public static void main(String[] args) {

        WechatCodeSetting wechatSetting = new WechatCodeSetting();
        wechatSetting.setComponent_appid("wx6007249d6b2348ea");
        wechatSetting.setComponent_appsecret("1b1c5e732f38a03c980061855e68a19a");

        System.out.printf(getDraftList(wechatSetting));

    }
}
